package com.beerandjesus.sportofkings.handicapper.dao;

import com.beerandjesus.sportofkings.handicapper.dao.aspect.TransactionBoundary;
import com.beerandjesus.sportofkings.handicapper.model.TurfSire;
import com.beerandjesus.sportofkings.handicapper.model.TurfSireImpl;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Date: Jun 7, 2012
 * Time: 6:29:37 PM
 */
public class TurfSireDAOImpl extends AbstractDAOImpl implements TurfSireDAO {

    private BaseSireDataFactory factory = new BaseSireDataFactory();
    private String[] baseDataFiles;

    @TransactionBoundary(datasources= Database.Datasource.TURF_SIRE)
    public void buildDatabase() throws DAOException {
        Connection connection = getConnectionManager().getTurfSireDatabaseConnection();
        if (getBaseDataFiles() == null || getBaseDataFiles().length == 0) {
            throw new DAOException("No base data files provided");
        }
        executeStatementIgnoringException(connection, DROP_TABLE_STMT);
        executeStatement(connection, CREATE_TABLE_STMT);
        PreparedStatement insert;
        try {
            List<BaseSireData> sires = factory.getBaseSireData(getBaseDataFiles());
            for (BaseSireData d : sires) {
                BigDecimal percentage = factory.getWinPercentage(d);
                insert = connection.prepareStatement("insert into " + LEADING_TURF_SIRES +
                        " (name, percentage) values (?, ?)");
                try {
                    insert.setString(1, d.getName());
                    insert.setBigDecimal(2, percentage);
                    insert.execute();
                } finally {
                    insert.close();
                }
            }
        } catch (IOException e) {
            throw new DAOException("Error reading base data file", e);
        } catch (SQLException e) {
            throw new DAOException("Error inserting data", e);
        }


    }

    @TransactionBoundary(datasources= Database.Datasource.TURF_SIRE)
    public int getRowCount() throws DAOException {
        Connection connection = getConnectionManager().getTurfSireDatabaseConnection();
        return getRowCount(connection, LEADING_TURF_SIRES);
    }

    public TurfSire getTurfSireByName(String name) throws DAOException {
        Connection connection = getConnectionManager().getTurfSireDatabaseConnection();
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        PreparedStatement smt = null;
        try {
            smt = connection.prepareStatement("select * from " + LEADING_TURF_SIRES + " where name = ?");
            smt.setString(1, name.toUpperCase());
            ResultSet rs = smt.executeQuery();
            try {
                if (rs == null || !rs.next()) {
                    return null;
                }
                String h = rs.getString("name");
                BigDecimal p = rs.getBigDecimal("percentage");
                TurfSireImpl ts = new TurfSireImpl();
                ts.setName(h);
                ts.setWinPercentage(p);
                return ts;
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        // ignore
                    }
                }
            }
        } catch (SQLException e) {
            throw new DAOException("Error fetching sire by name " + name, e);
        } finally {
            if (smt != null) {
                try {
                    smt.close();
                } catch (SQLException e) {
                    // ignore
                }
            }
        }
    }

    public String[] getBaseDataFiles() {
        return baseDataFiles;
    }

    public void setBaseDataFiles(String[] baseDataFiles) {
        this.baseDataFiles = baseDataFiles;
    }

}
